var app = getApp();
var WxParse = require('../../../../lib/wxParse/wxParse.js');
var util = require('../../../../utils/util.js');
var api = require('../../../../config/api.js');
var user = require('../../../../utils/user.js');
const dianpu = require('../../../../utils/common/dianpu.js');
const draw = require('../../../../utils/common/drawhaibao.js');

var lastTime = null;
Page({
  data: {
    id: '',
    pintuan: {},
    goods: {},
    lunbotu: [],
    canshu: [],
    tuijianGoods: [],
    memberUserid: '',
    number: 1,
    lowbuynum: 1,
    opendgg: false,
    openShare: false,
    openTwocodeimg: false,
    shareImage: '',
    canWrite: false, //用户是否获取了保存相册的权限
    timeout: false,
    shouqing: false,
    ispintuan: true,
    iskaituan: false, //开团页面，控制是否显示拼团按钮，false为显示拼团按钮
    mtTuzhang_pintuan: {}, //开团信息
    isyaoqing: false, //控制显示邀请好友参团还是显示显示参与好友拼团，false为显示邀请好友参团
    fukucunsale: true, //true为允许负库存销售；false为不允许
    countdown: '',
    endTime: '3000-01-01 00:00:00',
    kaituanendTime: '3000-01-01 00:00:00',
    day: '00',
    hour: '00',
    minute: '00',
    second: '00',
    kaituanday: '00',
    kaituanhour: '00',
    kaituanminute: '00',
    kaituansecond: '00',
    webstore: '',
    template: {},
    image: "",
    zhutu: "",
    twoCodeUrl: "",
    shareUserId: '',
    page: 1,
    limit: 10
  },

  // 获取商品信息
  getGoodsInfo: function () {
    let that = this;
    util.request(api.PintuanGoodsDetail, {
      id: that.data.id
    }).then(function (res) {
      if (res) {
        if (res.result == 1) {
          var _canshu = [];
          var _lunbotu = [];
          if (res.data.goods.canshuList.length > 0) {
            _canshu = JSON.parse(res.data.goods.canshuList);
          }
          if (res.data.goods.lunbotu.length > 0) {
            _lunbotu = JSON.parse(res.data.goods.lunbotu);
          }
          that.setData({
            pintuan: res.data.pintuan,
            goods: res.data.goods,
            fukucunsale: res.data.fukucunsale,
            endTime: res.data.pintuan.endTime,
            xianzhigoumainum: res.data.pintuan.xianzhigoumainum,
            lunbotu: _lunbotu,
            canshu: _canshu,
            ggname: res.data.goods.ggname,
          });
          if (res.data.goods.kucun < that.data.number) {
            if (!that.data.fukucunsale) {
              that.setData({
                shouqing: true
              });
            }
          }
          WxParse.wxParse('goodsDetail', 'html', res.data.goods.xiangxijieshao, that);
          //获取推荐商品
          that.getGoodsTuijian();
        }
      }
    });
  },

  // 获取推荐商品
  getGoodsTuijian: function () {
    let that = this;
    util.request(api.GoodsTuijian, {
      "id": that.data.goods.id,
      "page": that.data.page,
      "limit": that.data.limit
    }).then(function (res) {
      if (res.result == 1) {
        if (res.data.length > 0) {
          that.setData({
            tuijianGoods: that.data.tuijianGoods.concat(res.data),
            page: that.data.page + 1
          });
        } else {
          // wx.showToast({
          //   title: '已经被您看完了!',
          //   icon: 'none',
          //   duration: 2000
          // });
          return false;
        }
      }
    });
  },

  //点击电话图标
  tel: function () {
    wx.makePhoneCall({
      phoneNumber: '13242720897',
    })
  },

  //单独购买
  dandugoumai: function (e) {
    var that = this;
    if (that.data.opendgg == false) {
      //打开规格选择窗口
      that.setData({
        opendgg: !that.data.opendgg
      });
    } else {
      util.jhxLoadShow("加载中...");
      let nowTime = +new Date();
      if (nowTime - lastTime > 5000 || !lastTime) { //5秒内避免重复提交订单
        lastTime = nowTime;
      } else {
        return false;
      }
      util.request(api.MarketingShoppingCartBuyAdd, {
          number: that.data.number,
          price: that.data.goods.xiaoshoujia,
          pk_marketing: that.data.id,
          tablename: "mt_pintuan",
          buytype: 1
        }, "POST")
        .then(function (res) {
          if (res.result == 1) {
            that.setData({
              opendgg: !that.data.opendgg
            });
            // 如果storage中设置了shoppingcartid，则是立即购买，否则是购物车购买
            wx.setStorageSync('shoppingcartid', res.data.shoppingcartid);
            wx.navigateTo({
              url: '/pages/marketing/mtorder/mtorder'
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: res.errmsg,
              mask: true
            });
          }
        });
    }
  },
  //开团
  kaituan: function (e) {
    var that = this;
    if (that.data.opendgg == false) {
      //打开规格选择窗口
      that.setData({
        opendgg: !that.data.opendgg
      });
    } else {
      util.jhxLoadShow("加载中...");
      let nowTime = +new Date();
      if (nowTime - lastTime > 5000 || !lastTime) { //5秒内避免重复提交订单
        lastTime = nowTime;
      } else {
        return false;
      }
      util.request(api.MarketingShoppingCartBuyAdd, {
          number: that.data.number,
          price: that.data.pintuan.pintuanprice - that.data.pintuan.tuanzhangyouhuiprice,
          pk_marketing: that.data.id,
          tablename: "mt_pintuan",
          buytype: 0
        }, "POST")
        .then(function (res) {
          if (res.result == 1) {
            that.setData({
              opendgg: !that.data.opendgg
            });
            // 如果storage中设置了shoppingcartid，则是立即购买，否则是购物车购买
            wx.setStorageSync('shoppingcartid', res.data.shoppingcartid);
            wx.navigateTo({
              url: '/pages/marketing/mtorder/mtorder'
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: res.errmsg,
              mask: true
            });
          }
        });
    }
  },
  //参与好友拼团
  canyupintuan: function (e) {
    var that = this;
    if (that.data.opendgg == false) {
      //打开规格选择窗口
      that.setData({
        opendgg: !that.data.opendgg
      });
    } else {
      util.request(api.MarketingShoppingCartBuyAdd, {
          number: that.data.number,
          price: that.data.pintuan.pintuanprice,
          buytype: 2, //带上此参数用于获取跟团人的开团id返回来
          pk_marketing: that.data.id,
          tablename: "mt_pintuan",
          shareUserId: that.data.shareUserId
        }, "POST")
        .then(function (res) {
          if (res.result == 1) {
            that.setData({
              opendgg: !that.data.opendgg
            });
            // 如果storage中设置了shoppingcartid，则是立即购买，否则是购物车购买
            wx.setStorageSync('shoppingcartid', res.data.shoppingcartid);
            /**
             * 此参数传至订单页面，是为了记录下来这笔订单是有哪个拼团而来的，以及该团的团长、团的有效时间、需要多少人拼团才能成
             * 以及记录下来哪些会员跟了这个团进行下订单。匹配信息是当前拼团的id已及开团会员id为组合主键（拼团活动专用）
             */
            var pk_mtTuzhang_pintuan = res.data.pk_mtTuzhang_pintuan;
            wx.navigateTo({
              url: '/pages/marketing/mtorder/mtorder?pk_mtTuzhang_pintuan=' + pk_mtTuzhang_pintuan
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: res.errmsg,
              mask: true
            });
          }
        });
    }
  },

  //减数量
  cutNumber: function () {
    let that = this;
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },

  //加数量
  addNumber: function () {
    let that = this;
    if (that.data.number < that.data.xianzhigoumainum) {
      this.setData({
        number: this.data.number + 1
      });
    } else {
      this.setData({
        number: that.data.xianzhigoumainum
      });
    }

  },

  //切换显示规格窗口
  switchdgg: function () {
    if (this.data.opendgg == false) {
      this.setData({
        opendgg: !this.data.opendgg
      });
    }
  },

  //关闭规格窗口
  closedgg: function () {
    this.setData({
      opendgg: false,
    });
  },

  //跳转购物车
  openCartPage: function () {
    wx.switchTab({
      url: '/pages/shoppingcart/shoppingcart'
    });
  },

  // 页面分享
  onShareAppMessage: function (e) {
    let that = this;
    //邀请好友参团分享
    /**
      首先判断该活动是否已开团iskaituan为true时表示已开团，如果已开团的则需要带上isyaoqing参数，后面其他会员通过
      点击分享页面进来时会根据该参数判断是否已开团，如果已开团则不再显示拼团（开团）按钮，而是显示邀请，或者参与拼团按钮
    */
    if (that.data.iskaituan) {
      return {
        title: that.data.goods.goodsname,
        desc: '好东西要一起分享！',
        path: '/pages/marketing/pintuan/pintuanDetail/pintuanDetail?id=' + that.data.id + '&shareMemberUserid=' + that.data.memberUserid + '&isyaoqing=isyaoqing'
      }
    } else {
      return {
        title: that.data.goods.goodsname,
        desc: '好东西要一起分享！',
        path: '/pages/marketing/pintuan/pintuanDetail/pintuanDetail?id=' + that.data.id + '&shareMemberUserid=' + that.data.memberUserid
      }
    }
  },

  shareFriendOrCircle: function () {
    let that = this;
    if (that.data.openShare === false) {
      this.setData({
        openShare: !this.data.openShare
      });
    } else {
      return false;
    }
  },

  //微信小程序保存图片时会自动判断用户是否已同意保存到相处的权限
  handleSetting: function (e) {
    var that = this;
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '不授权无法保存',
        showCancel: false
      })
      that.setData({
        canWrite: false
      })
    } else {
      wx.showToast({
        title: '保存成功'
      })
      that.setData({
        canWrite: true
      })
    }
  },

  closeShare: function () {
    this.setData({
      openShare: false,
    });
    wx.hideLoading()
  },

  closetwocodeimg: function () {
    this.setData({
      openTwocodeimg: false,
    });
    wx.hideLoading()
  },

  // 生成成功
  canvasSuc(e) {
    wx.hideLoading()
    this.setData({
      image: e.detail.path
    })
  },

  // 点击保存海报弹出展示海报图片窗口
  getSave() {
    let that = this;
    that.setData({
      openShare: false
    });
    wx.showLoading({
      title: '正在努力生成中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1000);
    var isyaoqing = ''
    if (that.data.iskaituan) {
      isyaoqing = 'isyaoqing'
    }
    var scene = {
      "page": "pintuanDetail",
      "page_data_id": that.data.id,
      "othersign": isyaoqing
    };
    util.request(api.CreateQcodeImg, {
      scene: JSON.stringify(scene)
    }, 'GET').then(function (res) {
      that.setData({
        twoCodeUrl: res.data
      });
      wx.getSetting({
        success: function (res) {
          //不存在相册授权
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function () {
                var drawtemplate = draw.getMarketingDraw(that.data.goods.zhutu, that.data.pintuan.pintuanprice, that.data.goods.xiaoshoujia, that.data.goods.goodsname, that.data.twoCodeUrl);
                that.setData({
                  canWrite: true,
                  template: drawtemplate
                })
              },
              fail: function (err) {
                // 授权失败
                wx.showModal({
                  title: '警告',
                  content: '您点击了拒绝授权,将无法正常保存图片,点击确定重新获取授权。',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (res) => {
                          console.log('授权成功')
                        }
                      })
                    }
                  }
                })
              }
            })
          } else {
            var drawtemplate = draw.getMarketingDraw(that.data.goods.zhutu, that.data.pintuan.pintuanprice, that.data.goods.xiaoshoujia, that.data.goods.goodsname, that.data.twoCodeUrl);
            that.setData({
              canWrite: true,
              openTwocodeimg: true,
              template: drawtemplate
            });
          }
        }
      })
    });
  },

  //保存海报
  savehaibao: function () {
    let that = this;
    wx.getSetting({
      success: (set) => {
        wx.saveImageToPhotosAlbum({
          filePath: that.data.image,
          success: (res) => {
            if (res.errMsg == "saveImageToPhotosAlbum:ok") {
              wx.showModal({
                title: '存图成功',
                content: '图片成功保存到相册了，可以分享到朋友圈了',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#a78845',
                success: function (res) {
                  if (res.confirm) {}
                }
              })
            }
          }
        })
        if (set.authSetting['scope.writePhotosAlbum'] == false) {
          wx.openSetting()
        }
      }
    })
  },

  //长按画布中的图片
  previewImg() {
    wx.previewImage({
      current: this.data.image,
      urls: [this.data.image]
    })
  },
 
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },

  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    let that = this;
    //获取该登录会员的缓存id
    let memberUserid = wx.getStorageSync('memberUserid');
    that.setData({
      memberUserid: memberUserid
    });
    //该拼团活动的id
    if (options.id) {
      that.setData({
        id: options.id
      });
    }
    //如果存在shareMemberUserid值则表明是从点击分享的页面进来
    if (options.shareMemberUserid) {
      //分享连接中的参数，记录的是分享该页面的会员id
      that.setData({
        shareUserId: options.shareMemberUserid
      });
      //这个shareMemberUserid的存在证明是通过分享页面进来的,没有的则是从二维码中扫码进来的
      //保存分享信息，为以后做分享有礼功能的数据记录
      util.request(api.Yemianfenxiang, {
        shareMemberUserid: options.shareMemberUserid,
        page_data_id: options.id,
        page: 'pintuanDetail'
      }, 'GET').then(function (res) {
        if (res.result == 1) {

        }
      });
      //当前登录会员是否与分享页面中的会员参数相同，如果相同则显示邀请按钮，如果不同则显示是否参与拼团按钮
      if (that.data.memberUserid != options.shareMemberUserid) {
        that.setData({
          isyaoqing: true
        })
      }
    }
    //如果存在isyaoqing值则表明是从海报二维码中进来
    if (options.isyaoqing) {
      //home中通过扫海报二维码带过来的参数shareUserid，判断当前人员是否就是分享的人员，如果是则显示邀请按钮
      if (options.shareUserid) {
        //当前登录会员是否与分享海报二维码中的会员参数相同，如果相同则显示邀请按钮，如果不同则显示是否参与拼团按钮
        if (that.data.memberUserid != options.shareUserid) {
          //这个isyaoqing的存在证明是通过扫描二维码进来，且生成二维码时该页面状态为已开团
          that.setData({
            isyaoqing: true
          })
        }
      }
      //海报二维码中的分享人员参数，记录的是分享的会员id
      that.setData({
        shareUserId: options.shareUserid
      })
    }
  },

  onShow: function () {
    // 页面显示
    var that = this;
    if (Object.keys(that.data.goods).length == 0) {
      //获取页面详细信息
      that.getGoodsInfo();
    }
    // 检查是否已开团
    that.checkiskaituan();
  },

  checkiskaituan: function () {
    // 检查是否已开团
    var that = this;
    var pk_pintuan = that.data.id;
    //判断是否开团后进行的邀请，如果是则会带上分享人的id
    var shareUserId = '';
    //获取分享人的userid,此id为表mn_mt_tuanzhang_pintuan中的memberUserid
    if (that.data.shareUserId) {
      shareUserId = that.data.shareUserId;
    } else {
      shareUserId = that.data.memberUserid;
    }
    //根据拼团id与开团会员的id即分享该页面的会员id，查询表mn_mt_tuanzhang_pintuan是否有存在相关信息，如果存在则表示已开团
    if (pk_pintuan) {
      util.request(api.PintuanTuanzhangPintuan, {
          pk_pintuan: pk_pintuan,
          shareUserId: shareUserId
        })
        .then(function (res) {
          if (res.result == 1) {
            //查询表mn_mt_tuanzhang_pintuan，存在信息则表明已开团，否则未开团，iskaituan：true是已开团，已开团的则不再显示拼团（开团）按钮
            that.setData({
              iskaituan: res.data.iskaituan
            })
            //如果已开团，则显示开团相关信息，即表mn_mt_tuanzhang_pintuan中的信息，如该团的结束时间，已拼团人数等
            if (res.data.iskaituan) {
              that.setData({
                kaituanendTime: res.data.mtTuzhang_pintuan.endTime,
                mtTuzhang_pintuan: res.data.mtTuzhang_pintuan
              })
            }
            //如果开团则显示该团的有效时间倒计时，否则显示该活动结束时间倒计时
            if (res.data.iskaituan) {
              //显示该团的有效倒计时
              that.kaituanendTime();
            } else {
              //显示该拼团活动的倒计时
              that.countTime();
            }
          }
        });
    }
  },

  // 下拉刷新
  onReachBottom() {
    let that = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    if (that.data.tuijianGoods.length > 0) {
      that.getGoodsTuijian();
    }
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  //点击电话图标
  tel: function () {
    dianpu.getmendiantel().then(res => {
      wx.makePhoneCall({
        phoneNumber: res.lianxirenmobile,
      })
    }).catch(() => {
      wx.showToast({
        title: '获取联系方式失败!',
        icon: 'none',
        duration: 2000
      });
    });
  },
  //拼团活动的倒计时
  countTime: function () {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.endTime); //设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差               
    var day, hour, minute, second;
    if (leftTime >= 0) {
      day = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      hour = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      minute = Math.floor(leftTime / 1000 / 60 % 60);
      second = Math.floor(leftTime / 1000 % 60);
      second = second < 10 ? "0" + second : second
      minute = minute < 10 ? "0" + minute : minute
      hour = hour < 10 ? "0" + hour : hour
      that.setData({
        hour: hour,
        minute: minute,
        second: second
      })
      if (day >= 99) {
        that.setData({
          day: 99
        })
      } else {
        that.setData({
          day: day
        })
      }
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 1000);
    } else {
      that.setData({
        day: '00',
        hour: '00',
        minute: '00',
        second: '00',
        timeout: true
      })
    }
  },
  //开团后的有效时间倒计时
  kaituanendTime: function () {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.kaituanendTime); //设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差               
    var kaituanday, kaituanhour, kaituanminute, kaituansecond;
    if (leftTime >= 0) {
      kaituanday = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      kaituanhour = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      kaituanminute = Math.floor(leftTime / 1000 / 60 % 60);
      kaituansecond = Math.floor(leftTime / 1000 % 60);
      kaituansecond = kaituansecond < 10 ? "0" + kaituansecond : kaituansecond
      kaituanminute = kaituanminute < 10 ? "0" + kaituanminute : kaituanminute
      kaituanhour = kaituanhour < 10 ? "0" + kaituanhour : kaituanhour
      that.setData({
        kaituanhour: kaituanhour,
        kaituanminute: kaituanminute,
        kaituansecond: kaituansecond
      })
      if (kaituanday >= 99) {
        that.setData({
          kaituanday: 99
        })
      } else {
        that.setData({
          kaituanday: kaituanday
        })
      }
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.kaituanendTime, 1000);
    } else {
      that.setData({
        kaituanday: '00',
        kaituanhour: '00',
        kaituanminute: '00',
        kaituansecond: '00'
      })
    }
  }
})